package com.resou.reader.choosegender;

import android.os.Message;
import android.util.Log;

import com.resou.reader.ReSouApplication;
import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.GenderCategory;
import com.resou.reader.api.entry.LargessBook;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.LoginResult;
import com.resou.reader.api.service.GenderService;
import com.resou.reader.api.service.UserService;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.data.Injection;
import com.resou.reader.data.bookshelf.BookshelfRepository;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.TextUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.eventbus.LoadBookEvent;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

public class ChooseGenderPresenter extends ResouBasePresenter<ChooseContract.View> implements ChooseContract.Presenter {

    private final GenderService mService;
    private UserService userService;
    private List<GenderCategory> boyCategories;
    private List<GenderCategory> girlCategories;
    private static final String TAG = "ChooseGenderPresenter";

    public ChooseGenderPresenter(ChooseContract.View view) {
        super(view);
        mService = ApiImp.getInstance().getService(GenderService.class);
        userService = ApiImp.getInstance().getService(UserService.class);
    }

    @Override
    public void loadCategories(String gender) {
        if (gender.equals("1")) {
            if (boyCategories != null && boyCategories.size() > 0) {
                mView.setCategories(boyCategories);
                mView.showContent();
            } else {
                loadGenderCategories(gender);
            }
        }
        if (gender.equals("2")) {
            if (girlCategories != null && girlCategories.size() > 0) {
                mView.setCategories(girlCategories);
                mView.showContent();
            } else {
                loadGenderCategories(gender);
            }
        }
    }

    private void loadGenderCategories(String gender) {
        mView.showProgress();
        addCompositeDisposable(
                mService.getGenderCategories(gender)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(genderCategories -> {
                            if (genderCategories.getCode() == 0) {
                                List<GenderCategory> data = genderCategories.getData();
                                mView.setCategories(data);
                                mView.showContent();
                                if (gender.equals("1")) {
                                    boyCategories = data;
                                }
                                if (gender.equals("2")) {
                                    girlCategories = data;
                                }
                            } else {
                                ToastUtil.makeLongToast(genderCategories.getMsg());
                            }
                        }, throwable -> {
                            mView.showError(new Throwable("网络异常"));
                        }));
    }

    @Override
    public void skipChoose(String gender, String categoriesStr) {
        addCompositeDisposable(
                mService.getLargessBooks(gender, categoriesStr)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .subscribe(resultList -> {
                            if (resultList.getCode() == 0) {
                                List<LargessBook> data = resultList.getData();
                                //保存书籍到数据库
                                for (LargessBook book : data) {
                                    BookCollection bookCollection = LitePal.where("bookId = ?", book.getBookId()).findFirst(BookCollection.class);
                                    if (bookCollection != null) {
                                        bookCollection.setAuthor(book.getAuthorName());
                                        bookCollection.setBookId(book.getBookId());
                                        bookCollection.setName(book.getBookName());
                                        bookCollection.setPicUrl(book.getBookPic());
                                        bookCollection.setSerialStatus(book.getWhetherUpdate());
                                        bookCollection.setReadStatus(book.getReadStatus());
                                        bookCollection.setHistoryChapterName(book.getReadStatus());
                                        bookCollection.setChapterSum(0);
                                        bookCollection.setWhetherUpdate(book.getWhetherUpdate());
                                        bookCollection.setUserUpdateTime(System.currentTimeMillis());
//                                        if (book.getFreeStatus() == 0) {
//                                            bookCollection.setFreeStatus(true);
//                                        } else {
//                                            bookCollection.setFreeStatus(false);
//                                        }
                                        bookCollection.setFreeStatus(book.getFreeStatus());
                                        bookCollection.save();
                                    } else {
                                        BookCollection collection = new BookCollection();
                                        collection.setAuthor(book.getAuthorName());
                                        collection.setBookId(book.getBookId());
                                        collection.setName(book.getBookName());
                                        collection.setPicUrl(book.getBookPic());
                                        collection.setSerialStatus(book.getWhetherUpdate());
                                        collection.setReadStatus(book.getReadStatus());
                                        collection.setChapterSum(0);
                                        collection.setHistoryChapterName(book.getReadStatus());
//                                        if (book.getFreeStatus() == 0) {
//                                            collection.setFreeStatus(true);
//                                        } else {
//                                            collection.setFreeStatus(false);
//                                        }

                                        collection.setFreeStatus(book.getFreeStatus());
                                        collection.setWhetherUpdate(book.getWhetherUpdate());
                                        collection.setUserUpdateTime(System.currentTimeMillis());
                                        collection.save();
                                    }

                                    EventBus.getDefault().post(new Message());
                                    EventBus.getDefault().post(new LoadBookEvent());
                                }
                            } else {
//                                ToastUtil.makeShortToast(resultList.getMsg());
                            }
                        }, throwable -> {
//                            mView.showError(throwable);
                        })
        );
    }

    /**
     * 游客登录
     *
     * @param versionName
     */
    public void touristLogin(String versionName) {
        userService.touristLogin(DeviceUtils.getIMEI(ReSouApplication.getRSApplication()),
                "游客" + versionName, 100, "android").subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Observer<LoginResult<LoginData>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(LoginResult<LoginData> loginDataLoginResult) {
                        if (loginDataLoginResult.getCode() == 0) {
                            //登录成功后保存登录信息
                            /**
                             * 统计新增用户
                             */
                            MobclickAgent.onProfileSignIn("YK", loginDataLoginResult.getData().getId() + "");
                            MobclickAgent.onEvent(ReSouApplication.getRSApplication(), "user_login", "YK");
                            UserInstance.setLoginData(loginDataLoginResult.getData());
                            UserInstance.setToken(loginDataLoginResult.getToken());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(new Throwable("网络异常"));
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    /**
     * 获取五本书
     *
     * @param gender
     * @param categoriesStr
     */
    public void loadBooks(String gender, String categoriesStr) {
        addCompositeDisposable(
                mService.getLargessBooks2(UserInstance.getToken(), gender, categoriesStr)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(resultList -> {
                            if (resultList.getCode() == 0) {
                                mView.noAddBook();
                            } else {
                                mView.addBook();
                            }
                        }, throwable -> {
                            mView.showError(throwable);
                        })
        );
    }


}
